{% extends "base.html" %}
{% block title %}投诉类型分析 - {{ app_name }}{% endblock %}

{% block extra_css %}
<!-- 统一设计系统 -->
<link rel="stylesheet" href="/static/css/design-system/index.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.0/chart.min.css">

<!-- 投诉类型分析特定样式 -->
<style>
    :root {
        --complaint-primary: #3b82f6;
        --complaint-primary-light: #dbeafe;
        --complaint-primary-dark: #1e40af;
        --complaint-success: #10b981;
        --complaint-success-light: #d1fae5;
        --complaint-error: #ef4444;
        --complaint-error-light: #fee2e2;
        --complaint-warning: #f59e0b;
        --complaint-warning-light: #fef3c7;
    }

    .complaint-header {
        background: linear-gradient(135deg, var(--complaint-primary-dark) 0%, var(--complaint-primary) 100%);
        color: white;
        padding: 2rem 0;
        border-radius: 0 0 1rem 1rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }

    .stat-card-custom {
        background: white;
        border-radius: 1rem;
        padding: 1.5rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        border-left: 4px solid var(--complaint-primary);
        transition: transform 0.2s, box-shadow 0.2s;
    }

    .stat-card-custom:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .stat-value {
        font-size: 2.5rem;
        font-weight: 700;
        color: var(--color-text-primary);
        margin-bottom: 0.5rem;
    }

    .stat-label {
        font-size: 0.875rem;
        color: var(--color-text-secondary);
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .tab-container {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        overflow: hidden;
    }

    .custom-tabs {
        display: flex;
        background: var(--color-bg-tertiary);
        border-bottom: 1px solid var(--color-border-primary);
        flex-wrap: wrap;
    }

    .custom-tab {
        padding: 1rem 1.5rem;
        cursor: pointer;
        border: none;
        background: none;
        color: var(--color-text-secondary);
        font-weight: 500;
        transition: all 0.2s;
        position: relative;
        flex: 1;
        min-width: 120px;
        text-align: center;
    }

    .custom-tab:hover {
        color: var(--complaint-primary);
        background: var(--color-bg-secondary);
    }

    .custom-tab.active {
        color: var(--complaint-primary);
        background: white;
    }

    .custom-tab.active::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: var(--complaint-primary);
    }

    .tab-content-custom {
        padding: 2rem;
        min-height: 500px;
    }

    .complaint-badge {
        padding: 0.25rem 0.75rem;
        border-radius: 1rem;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .complaint-badge.high {
        background: var(--complaint-error-light);
        color: var(--complaint-error);
    }

    .complaint-badge.medium {
        background: var(--complaint-warning-light);
        color: var(--complaint-warning);
    }

    .complaint-badge.low {
        background: var(--complaint-success-light);
        color: var(--complaint-success);
    }

    .compliance-item {
        padding: 1rem;
        border-bottom: 1px solid var(--color-border-secondary);
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: background 0.2s;
    }

    .compliance-item:hover {
        background: var(--color-bg-secondary);
    }

    .compliance-item:last-child {
        border-bottom: none;
    }

    .compliance-name {
        font-weight: 500;
        color: var(--color-text-primary);
    }

    .compliance-metrics {
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .compliance-rate {
        font-size: 0.875rem;
        font-weight: 600;
        padding: 0.25rem 0.5rem;
        border-radius: 0.5rem;
        background: var(--color-bg-tertiary);
    }

    .compliance-rate.high {
        background: var(--complaint-success-light);
        color: var(--complaint-success);
    }

    .compliance-rate.medium {
        background: var(--complaint-warning-light);
        color: var(--complaint-warning);
    }

    .compliance-rate.low {
        background: var(--complaint-error-light);
        color: var(--complaint-error);
    }

    /* 筛选面板 */
    .filter-section {
        background: white;
        border-radius: 1rem;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .filter-title {
        font-size: 1.125rem;
        font-weight: 600;
        color: var(--color-text-primary);
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .filter-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1rem;
        margin-bottom: 1rem;
    }

    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .filter-label {
        font-size: 0.875rem;
        font-weight: 500;
        color: var(--color-text-secondary);
    }

    .filter-input {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border-primary);
        border-radius: 0.5rem;
        font-size: 0.875rem;
        transition: border-color 0.2s;
    }

    .filter-input:focus {
        outline: none;
        border-color: var(--complaint-primary);
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    .filter-actions {
        display: flex;
        gap: 1rem;
        justify-content: flex-end;
        margin-top: 1rem;
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .compliance-trend {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .trend-up {
        color: var(--complaint-success);
    }

    .trend-down {
        color: var(--complaint-error);
    }

    .trend-neutral {
        color: var(--color-text-secondary);
    }

    /* 图表容器 */
    .chart-wrapper {
        position: relative;
        height: 400px;
        margin-bottom: 1rem;
    }

    .chart-actions {
        position: absolute;
        top: 1rem;
        right: 1rem;
        display: flex;
        gap: 0.5rem;
        z-index: 10;
    }

    .chart-action {
        background: white;
        border: 1px solid var(--color-border-primary);
        border-radius: 0.375rem;
        padding: 0.5rem;
        cursor: pointer;
        transition: all 0.2s;
        color: var(--color-text-secondary);
    }

    .chart-action:hover {
        background: var(--color-bg-secondary);
        color: var(--color-text-primary);
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .complaint-header {
            padding: 1.5rem 0;
        }

        .stat-value {
            font-size: 2rem;
        }

        .custom-tabs {
            flex-direction: column;
        }

        .custom-tab {
            flex: none;
            text-align: left;
        }

        .tab-content-custom {
            padding: 1rem;
        }

        .filter-row {
            grid-template-columns: 1fr;
        }

        .filter-actions {
            flex-direction: column;
        }

        .stats-grid {
            grid-template-columns: 1fr;
        }
    }

    /* 加载动画 */
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
        opacity: 0;
        visibility: hidden;
        transition: opacity 0.3s, visibility 0.3s;
    }

    .loading-overlay.active {
        opacity: 1;
        visibility: visible;
    }

    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 4px solid rgba(255, 255, 255, 0.3);
        border-top: 4px solid white;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* 空状态 */
    .empty-state {
        text-align: center;
        padding: 3rem;
        color: var(--color-text-secondary);
    }

    .empty-state i {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    /* 投诉类型标签 */
    .complaint-type-tag {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 0.5rem;
        font-size: 0.75rem;
        font-weight: 500;
        background: var(--complaint-primary-light);
        color: var(--complaint-primary);
        margin: 0.25rem;
        cursor: pointer;
        transition: all 0.2s;
    }

    .complaint-type-tag:hover {
        background: var(--complaint-primary);
        color: white;
        transform: translateY(-1px);
    }

    /* 分页样式 */
    .pagination-custom {
        display: flex;
        justify-content: center;
        gap: 0.5rem;
        margin-top: 2rem;
    }

    .page-btn {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--color-border-primary);
        background: white;
        color: var(--color-text-primary);
        border-radius: 0.375rem;
        cursor: pointer;
        transition: all 0.2s;
    }

    .page-btn:hover {
        background: var(--color-bg-secondary);
    }

    .page-btn.active {
        background: var(--complaint-primary);
        color: white;
        border-color: var(--complaint-primary);
    }

    .page-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    /* 进度条 */
    .progress-custom {
        width: 100%;
        height: 8px;
        background: var(--color-bg-tertiary);
        border-radius: 4px;
        overflow: hidden;
        margin: 0.5rem 0;
    }

    .progress-bar-custom {
        height: 100%;
        background: var(--complaint-primary);
        border-radius: 4px;
        transition: width 0.3s;
    }

    .progress-bar-custom.success {
        background: var(--complaint-success);
    }

    .progress-bar-custom.error {
        background: var(--complaint-error);
    }

    .progress-bar-custom.warning {
        background: var(--complaint-warning);
    }
</style>
{% endblock %}

{% block content %}
<!-- 页面头部 -->
<div class="complaint-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="h2 mb-2">
                    <i class="fas fa-tags me-2"></i>投诉类型分析
                </h1>
                <p class="mb-0 opacity-90">深度分析信访投诉类型分布，洞察问题热点和趋势变化</p>
            </div>
            <div class="col-md-4 text-md-end">
                <div class="d-flex align-items-center justify-content-md-end gap-3">
                    <div class="text-center">
                        <div class="h4 mb-0" id="lastUpdate">-</div>
                        <small>最后更新</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 主要内容 -->
<div class="container my-4">
    <!-- 筛选面板 -->
    <div class="filter-section">
        <div class="filter-title">
            <i class="fas fa-filter"></i>分析筛选
        </div>
        <div class="filter-row">
            <div class="filter-group">
                <label class="filter-label">分析任务</label>
                <select class="filter-input" id="taskSelect">
                    <option value="">全部任务</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="filter-label">开始日期</label>
                <input type="date" class="filter-input" id="startDate">
            </div>
            <div class="filter-group">
                <label class="filter-label">结束日期</label>
                <input type="date" class="filter-input" id="endDate">
            </div>
            <div class="filter-group">
                <label class="filter-label">投诉类型</label>
                <select class="filter-input" id="complaintType">
                    <option value="">全部类型</option>
                </select>
            </div>
        </div>
        <div class="filter-row">
            <div class="filter-group">
                <label class="filter-label">优先级</label>
                <select class="filter-input" id="priority">
                    <option value="">全部优先级</option>
                    <option value="high">高</option>
                    <option value="medium">中</option>
                    <option value="low">低</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="filter-label">关键词过滤</label>
                <input type="text" class="filter-input" id="keywordFilter" placeholder="输入关键词进行过滤">
            </div>
            <div class="filter-group">
                <label class="filter-label">最低置信度</label>
                <input type="number" class="filter-input" id="minConfidence" placeholder="0.0 - 1.0" step="0.1" min="0" max="1">
            </div>
        </div>
        <div class="filter-actions">
            <button class="btn btn-secondary" onclick="resetFilters()">
                <i class="fas fa-redo me-1"></i>重置
            </button>
            <button class="btn btn-primary" onclick="loadAnalysis()">
                <i class="fas fa-search me-1"></i>开始分析
            </button>
        </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-grid" id="statsGrid">
        <div class="stat-card-custom">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value" id="totalRecords">-</div>
                    <div class="stat-label">总记录数</div>
                </div>
                <div class="text-primary">
                    <i class="fas fa-file-alt fa-2x"></i>
                </div>
            </div>
            <div class="compliance-trend mt-2" id="totalTrend">
                <i class="fas fa-minus"></i>
                <span>较上期</span>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value" id="totalTypes">-</div>
                    <div class="stat-label">投诉类型数</div>
                </div>
                <div class="text-warning">
                    <i class="fas fa-layer-group fa-2x"></i>
                </div>
            </div>
            <div class="compliance-trend mt-2" id="typesTrend">
                <i class="fas fa-minus"></i>
                <span>较上期</span>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value" id="avgConfidence">-</div>
                    <div class="stat-label">平均置信度</div>
                </div>
                <div class="text-info">
                    <i class="fas fa-brain fa-2x"></i>
                </div>
            </div>
            <div class="compliance-trend mt-2" id="confidenceTrend">
                <i class="fas fa-minus"></i>
                <span>较上期</span>
            </div>
        </div>

        <div class="stat-card-custom">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value" id="topType">-</div>
                    <div class="stat-label">主要类型</div>
                </div>
                <div class="text-danger">
                    <i class="fas fa-exclamation-triangle fa-2x"></i>
                </div>
            </div>
            <div class="progress-custom mt-2">
                <div class="progress-bar-custom" id="topTypeProgress" style="width: 0%"></div>
            </div>
        </div>
    </div>

    <!-- 分析标签页 -->
    <div class="tab-container">
        <div class="custom-tabs">
            <button class="custom-tab active" data-tab="distribution">
                <i class="fas fa-chart-pie me-1"></i>类型分布
            </button>
            <button class="custom-tab" data-tab="trends">
                <i class="fas fa-chart-line me-1"></i>趋势分析
            </button>
            <button class="custom-tab" data-tab="priority">
                <i class="fas fa-flag me-1"></i>优先级分析
            </button>
            <button class="custom-tab" data-tab="keywords">
                <i class="fas fa-hashtag me-1"></i>关键词分析
            </button>
            <button class="custom-tab" data-tab="details">
                <i class="fas fa-list me-1"></i>详情列表
            </button>
        </div>

        <div class="tab-content-custom">
            <!-- 类型分布 -->
            <div id="distribution" class="tab-pane">
                <div class="row">
                    <div class="col-md-8">
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('typeDistribution')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('typeDistribution')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="typeDistributionChart"></canvas>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <h5 class="mb-3">类型排行</h5>
                        <div id="typeRanking"></div>

                        <h5 class="mb-3 mt-4">分类统计</h5>
                        <div id="categoryStats"></div>
                    </div>
                </div>
            </div>

            <!-- 趋势分析 -->
            <div id="trends" class="tab-pane" style="display: none;">
                <div class="row">
                    <div class="col-md-8">
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('typeTrends')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('typeTrends')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="typeTrendsChart"></canvas>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <h5 class="mb-3">趋势统计</h5>
                        <div id="trendStats"></div>

                        <h5 class="mb-3 mt-4">变化率</h5>
                        <div id="changeRates"></div>
                    </div>
                </div>
            </div>

            <!-- 优先级分析 -->
            <div id="priority" class="tab-pane" style="display: none;">
                <div class="row">
                    <div class="col-md-8">
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('priorityAnalysis')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('priorityAnalysis')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="priorityAnalysisChart"></canvas>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <h5 class="mb-3">优先级分布</h5>
                        <div id="priorityDistribution"></div>

                        <h5 class="mb-3 mt-4">高优先级类型</h5>
                        <div id="highPriorityTypes"></div>
                    </div>
                </div>
            </div>

            <!-- 关键词分析 -->
            <div id="keywords" class="tab-pane" style="display: none;">
                <div class="row">
                    <div class="col-md-8">
                        <div class="chart-wrapper">
                            <div class="chart-actions">
                                <button class="chart-action" onclick="refreshChart('keywordAnalysis')" title="刷新">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="chart-action" onclick="downloadChart('keywordAnalysis')" title="下载">
                                    <i class="fas fa-download"></i>
                                </button>
                            </div>
                            <canvas id="keywordAnalysisChart"></canvas>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <h5 class="mb-3">热门关键词</h5>
                        <div id="keywordRanking"></div>

                        <h5 class="mb-3 mt-4">关键词云</h5>
                        <div id="keywordCloud"></div>
                    </div>
                </div>
            </div>

            <!-- 详情列表 -->
            <div id="details" class="tab-pane" style="display: none;">
                <div class="row">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0">投诉类型详情</h5>
                            <div class="d-flex gap-2">
                                <button class="btn btn-sm btn-outline-primary" onclick="exportDetails()">
                                    <i class="fas fa-file-export me-1"></i>导出
                                </button>
                                <button class="btn btn-sm btn-outline-secondary" onclick="refreshDetails()">
                                    <i class="fas fa-refresh me-1"></i>刷新
                                </button>
                            </div>
                        </div>
                        <div id="complaintDetails"></div>

                        <!-- 分页控件 -->
                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <div class="text-muted" id="detailsInfo"></div>
                            <div class="d-flex gap-2" id="detailsPagination"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 加载遮罩 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>
{% endblock %}

{% block extra_js %}
<!-- 引入必要的库 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.0/chart.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>

<!-- 引入组件库 -->
<script src="/static/js/components/base/BaseComponent.js"></script>
<script src="/static/js/components/base/StatCard.js"></script>
<script src="/static/js/components/base/FilterPanel.js"></script>
<script src="/static/js/components/base/ChartContainer.js"></script>

<!-- 引入工具类 -->
<script src="/static/js/utils/ApiClient.js"></script>
<script src="/static/js/utils/CacheManager.js"></script>
<script src="/static/js/utils/ErrorHandler.js"></script>

<script>
// 全局变量
let apiClient;
let cacheManager;
let errorHandler;
let charts = {};
let currentData = null;
let currentPage = 1;
let pageSize = 10;

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
async function initializeApp() {
    try {
        // 初始化工具类
        apiClient = new ApiClient({
            baseUrl: '/api',
            timeout: 30000,
            refreshToken: refreshToken
        });

        cacheManager = new CacheManager({
            prefix: 'complaint-analysis',
            ttl: 300000 // 5分钟缓存
        });

        errorHandler = new ErrorHandler({
            enableLogging: true,
            enableNotification: true,
            enableReporting: false
        });

        // 设置全局错误处理
        window.addEventListener('error', (event) => {
            errorHandler.handleError(event.error, '全局错误');
        });

        window.addEventListener('unhandledrejection', (event) => {
            errorHandler.handleError(event.reason, '未处理的Promise拒绝');
        });

        // 初始化页面
        await initializePage();

        console.log('投诉类型分析页面初始化完成');
    } catch (error) {
        console.error('应用初始化失败:', error);
        errorHandler.handleError(error, '应用初始化');
    }
}

// 初始化页面
async function initializePage() {
    try {
        // 设置默认日期
        setDefaultDates();

        // 加载分析任务
        await loadTasks();

        // 初始化图表
        initializeCharts();

        // 绑定事件
        bindEvents();

        // 加载默认数据
        await loadDefaultData();

        // 更新最后更新时间
        updateLastUpdateTime();
    } catch (error) {
        console.error('页面初始化失败:', error);
        errorHandler.handleError(error, '页面初始化');
    }
}

// 设置默认日期
function setDefaultDates() {
    const today = new Date();
    const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);

    document.getElementById('endDate').value = today.toISOString().split('T')[0];
    document.getElementById('startDate').value = thirtyDaysAgo.toISOString().split('T')[0];
}

// 加载分析任务
async function loadTasks() {
    try {
        const cacheKey = 'analysis-tasks';
        const cachedData = cacheManager.get(cacheKey);

        if (cachedData) {
            populateTaskSelect(cachedData);
            return;
        }

        const response = await apiClient.get('/analysis-tasks', {
            params: {
                status: 'completed',
                limit: 100
            }
        });

        if (response.success) {
            const tasks = response.data.tasks || response.data.items || response.data || [];
            cacheManager.set(cacheKey, tasks, 600000); // 10分钟缓存
            populateTaskSelect(tasks);
        }
    } catch (error) {
        console.error('加载任务失败:', error);
        errorHandler.handleError(error, '加载分析任务');
    }
}

// 填充任务选择框
function populateTaskSelect(tasks) {
    const taskSelect = document.getElementById('taskSelect');
    taskSelect.innerHTML = '<option value="">全部任务</option>';

    tasks.forEach(task => {
        const option = document.createElement('option');
        option.value = task.id;
        option.textContent = task.name || `任务 ${task.id}`;
        taskSelect.appendChild(option);
    });
}

// 初始化图表
function initializeCharts() {
    // 类型分布图表
    charts.typeDistribution = new Chart(
        document.getElementById('typeDistributionChart'),
        {
            type: 'doughnut',
            data: {
                labels: [],
                datasets: [{
                    data: [],
                    backgroundColor: [],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '投诉类型分布'
                    }
                }
            }
        }
    );

    // 趋势分析图表
    charts.typeTrends = new Chart(
        document.getElementById('typeTrendsChart'),
        {
            type: 'line',
            data: {
                labels: [],
                datasets: []
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    },
                    title: {
                        display: true,
                        text: '投诉类型趋势'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        }
    );

    // 优先级分析图表
    charts.priorityAnalysis = new Chart(
        document.getElementById('priorityAnalysisChart'),
        {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: '数量',
                    data: [],
                    backgroundColor: []
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '优先级分析'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        }
    );

    // 关键词分析图表
    charts.keywordAnalysis = new Chart(
        document.getElementById('keywordAnalysisChart'),
        {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: '频率',
                    data: [],
                    backgroundColor: '#3b82f6'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '关键词频率'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        }
    );
}

// 绑定事件
function bindEvents() {
    // 标签页切换
    document.querySelectorAll('.custom-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            switchTab(this.dataset.tab);
        });
    });

    // 监听筛选条件变化
    const filterInputs = ['taskSelect', 'startDate', 'endDate', 'complaintType', 'priority', 'keywordFilter', 'minConfidence'];
    filterInputs.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('change', debounceFilter);
            if (element.type === 'text' || element.type === 'number') {
                element.addEventListener('input', debounceFilter);
            }
        }
    });

    // 窗口大小改变时重新调整图表
    window.addEventListener('resize', debounce(() => {
        Object.values(charts).forEach(chart => {
            if (chart.resize) chart.resize();
        });
    }, 250));
}

// 防抖函数
function debounce(func, wait = 300) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 防抖筛选
const debounceFilter = debounce(() => {
    if (currentData) {
        loadAnalysis();
    }
}, 500);

// 加载默认数据
async function loadDefaultData() {
    try {
        await loadAnalysis();
    } catch (error) {
        console.error('加载默认数据失败:', error);
        showEmptyState('加载失败，请重试');
    }
}

// 加载分析数据
async function loadAnalysis() {
    showLoading(true);

    try {
        const filters = getFilters();
        const cacheKey = `complaint-analysis-${JSON.stringify(filters)}`;
        const cachedData = cacheManager.get(cacheKey);

        if (cachedData) {
            currentData = cachedData;
            updateDashboard(cachedData);
            updateAllCharts(cachedData);
            updateLastUpdateTime();
            showLoading(false);
            return;
        }

        const response = await apiClient.post('/complaint-analysis/analyze', filters);

        if (response.success) {
            currentData = response.data;
            cacheManager.set(cacheKey, response.data, 300000); // 5分钟缓存
            updateDashboard(response.data);
            updateAllCharts(response.data);
            updateLastUpdateTime();
        } else {
            throw new Error(response.message || '分析失败');
        }
    } catch (error) {
        console.error('分析失败:', error);
        errorHandler.handleError(error, '加载分析数据');
        showError('分析失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

// 获取筛选条件
function getFilters() {
    return {
        task_id: document.getElementById('taskSelect').value ? parseInt(document.getElementById('taskSelect').value) : null,
        start_date: document.getElementById('startDate').value || null,
        end_date: document.getElementById('endDate').value || null,
        complaint_type: document.getElementById('complaintType').value || null,
        priority: document.getElementById('priority').value || null,
        keyword_filter: document.getElementById('keywordFilter').value || null,
        min_confidence: document.getElementById('minConfidence').value ? parseFloat(document.getElementById('minConfidence').value) : null
    };
}

// 更新仪表板
function updateDashboard(data) {
    if (!data || !data.analysis_metadata) return;

    const metadata = data.analysis_metadata;

    // 更新统计卡片
    document.getElementById('totalRecords').textContent = (metadata.total_records || 0).toLocaleString();
    document.getElementById('totalTypes').textContent = Object.keys(data.type_distribution?.type_counts || {}).length;
    document.getElementById('avgConfidence').textContent = (metadata.average_confidence || 0).toFixed(3);

    // 更新主要类型
    const topType = getTopType(data.type_distribution?.type_counts || {});
    document.getElementById('topType').textContent = topType.name || '-';
    const topTypeProgress = document.getElementById('topTypeProgress');
    if (topType.percentage) {
        topTypeProgress.style.width = topType.percentage + '%';
        topTypeProgress.className = 'progress-bar-custom';
    }

    // 更新趋势指示器
    updateTrendIndicators(metadata);
}

// 获取主要类型
function getTopType(typeCounts) {
    const sortedTypes = Object.entries(typeCounts).sort(([,a], [,b]) => b - a);
    if (sortedTypes.length === 0) return { name: '-', percentage: 0 };

    const topType = sortedTypes[0];
    const total = Object.values(typeCounts).reduce((sum, count) => sum + count, 0);
    const percentage = total > 0 ? (topType[1] / total * 100) : 0;

    return { name: topType[0], percentage: percentage };
}

// 更新趋势指示器
function updateTrendIndicators(metadata) {
    // 这里可以根据实际数据计算趋势
    // 暂时显示中性趋势
    const trendElements = ['totalTrend', 'typesTrend', 'confidenceTrend'];
    trendElements.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            element.innerHTML = '<i class="fas fa-minus"></i><span>较上期</span>';
            element.className = 'compliance-trend mt-2 trend-neutral';
        }
    });
}

// 更新所有图表
function updateAllCharts(data) {
    updateTypeDistributionChart(data.type_distribution);
    updateTypeTrendsChart(data.trend_analysis);
    updatePriorityAnalysisChart(data.priority_analysis);
    updateKeywordAnalysisChart(data.keyword_analysis);
    updateTypeRanking(data.type_distribution);
    updateCategoryStats(data.type_distribution);
    updatePriorityDistribution(data.priority_analysis);
    updateHighPriorityTypes(data.priority_analysis);
    updateKeywordRanking(data.keyword_analysis);
    updateKeywordCloud(data.keyword_analysis);
}

// 更新类型分布图表
function updateTypeDistributionChart(data) {
    if (!data || !data.type_counts) return;

    const chart = charts.typeDistribution;
    const types = Object.keys(data.type_counts);
    const counts = Object.values(data.type_counts);

    chart.data.labels = types;
    chart.data.datasets[0].data = counts;
    chart.data.datasets[0].backgroundColor = generateColors(types.length);

    chart.update();
}

// 更新类型趋势图表
function updateTypeTrendsChart(data) {
    if (!data || !data.time_series) return;

    const chart = charts.typeTrends;
    const dates = data.time_series.map(item => item.date);
    const types = Object.keys(data.time_series[0]?.type_counts || {});

    const datasets = types.map((type, index) => ({
        label: type,
        data: data.time_series.map(item => item.type_counts[type] || 0),
        borderColor: getColorByIndex(index),
        backgroundColor: getColorByIndex(index, 0.1),
        fill: false,
        tension: 0.4
    }));

    chart.data.labels = dates;
    chart.data.datasets = datasets;
    chart.update();
}

// 更新优先级分析图表
function updatePriorityAnalysisChart(data) {
    if (!data || !data.priority_counts) return;

    const chart = charts.priorityAnalysis;
    const priorities = Object.keys(data.priority_counts);
    const counts = Object.values(data.priority_counts);

    chart.data.labels = priorities.map(p => getPriorityLabel(p));
    chart.data.datasets[0].data = counts;
    chart.data.datasets[0].backgroundColor = priorities.map(p => getPriorityColor(p));

    chart.update();
}

// 更新关键词分析图表
function updateKeywordAnalysisChart(data) {
    if (!data || !data.keyword_frequencies) return;

    const chart = charts.keywordAnalysis;
    const keywords = Object.keys(data.keyword_frequencies).slice(0, 15);
    const frequencies = keywords.map(keyword => data.keyword_frequencies[keyword]);

    chart.data.labels = keywords;
    chart.data.datasets[0].data = frequencies;

    chart.update();
}

// 更新类型排行
function updateTypeRanking(data) {
    const ranking = document.getElementById('typeRanking');
    if (!ranking || !data || !data.type_counts) return;

    const types = Object.keys(data.type_counts);
    const sortedTypes = types.sort((a, b) => data.type_counts[b] - data.type_counts[a]);

    let html = '';
    sortedTypes.slice(0, 10).forEach((type, index) => {
        const count = data.type_counts[type];
        html += `
            <div class="compliance-item">
                <div>
                    <div class="compliance-name">${index + 1}. ${type}</div>
                    <small class="text-muted">数量: ${count}</small>
                </div>
                <span class="compliance-rate medium">${count}</span>
            </div>
        `;
    });

    ranking.innerHTML = html;
}

// 更新分类统计
function updateCategoryStats(data) {
    const stats = document.getElementById('categoryStats');
    if (!stats || !data || !data.category_counts) return;

    const categories = Object.keys(data.category_counts);
    const total = Object.values(data.category_counts).reduce((sum, count) => sum + count, 0);

    let html = '';
    categories.forEach(category => {
        const count = data.category_counts[category];
        const percentage = total > 0 ? (count / total * 100).toFixed(1) : 0;
        html += `
            <div class="compliance-item">
                <div>
                    <div class="compliance-name">${category}</div>
                    <small class="text-muted">${count} 条记录</small>
                </div>
                <span class="compliance-rate high">${percentage}%</span>
            </div>
        `;
    });

    stats.innerHTML = html;
}

// 更新优先级分布
function updatePriorityDistribution(data) {
    const distribution = document.getElementById('priorityDistribution');
    if (!distribution || !data || !data.priority_counts) return;

    const priorities = Object.keys(data.priority_counts);
    const total = Object.values(data.priority_counts).reduce((sum, count) => sum + count, 0);

    let html = '';
    priorities.forEach(priority => {
        const count = data.priority_counts[priority];
        const percentage = total > 0 ? (count / total * 100).toFixed(1) : 0;
        const priorityClass = priority;

        html += `
            <div class="compliance-item">
                <div>
                    <div class="compliance-name">${getPriorityLabel(priority)}</div>
                    <small class="text-muted">${count} 条记录</small>
                </div>
                <span class="compliance-rate ${priorityClass}">${percentage}%</span>
            </div>
        `;
    });

    distribution.innerHTML = html;
}

// 更新高优先级类型
function updateHighPriorityTypes(data) {
    const highPriorityTypes = document.getElementById('highPriorityTypes');
    if (!highPriorityTypes || !data || !data.high_priority_types) return;

    const types = data.high_priority_types.slice(0, 5);
    let html = '';

    types.forEach(type => {
        html += `
            <div class="compliance-item">
                <div>
                    <div class="compliance-name">${type.type}</div>
                    <small class="text-muted">数量: ${type.count}</small>
                </div>
                <span class="complaint-badge high">${type.count}</span>
            </div>
        `;
    });

    highPriorityTypes.innerHTML = html;
}

// 更新关键词排行
function updateKeywordRanking(data) {
    const ranking = document.getElementById('keywordRanking');
    if (!ranking || !data || !data.keyword_frequencies) return;

    const keywords = Object.keys(data.keyword_frequencies).slice(0, 10);
    let html = '';

    keywords.forEach((keyword, index) => {
        const frequency = data.keyword_frequencies[keyword];
        html += `
            <div class="compliance-item">
                <div>
                    <div class="compliance-name">${index + 1}. ${keyword}</div>
                    <small class="text-muted">频率: ${frequency}</small>
                </div>
                <span class="compliance-rate medium">${frequency}</span>
            </div>
        `;
    });

    ranking.innerHTML = html;
}

// 更新关键词云
function updateKeywordCloud(data) {
    const cloud = document.getElementById('keywordCloud');
    if (!cloud || !data || !data.keyword_frequencies) return;

    const keywords = Object.keys(data.keyword_frequencies).slice(0, 20);
    const maxFreq = Math.max(...Object.values(data.keyword_frequencies));

    let html = '';
    keywords.forEach(keyword => {
        const frequency = data.keyword_frequencies[keyword];
        const size = Math.max(0.75, Math.min(1.5, frequency / maxFreq * 1.5));

        html += `<span class="complaint-type-tag" style="font-size: ${size}rem">${keyword}</span>`;
    });

    cloud.innerHTML = html;
}

// 更新趋势统计
function updateTrendStats(data) {
    const stats = document.getElementById('trendStats');
    if (!stats || !data || !data.trend_statistics) return;

    const statsHtml = `
        <div class="compliance-item">
            <div class="compliance-name">总增长率</div>
            <span class="compliance-rate ${data.trend_statistics.growth_rate >= 0 ? 'high' : 'low'}">${data.trend_statistics.growth_rate >= 0 ? '+' : ''}${data.trend_statistics.growth_rate.toFixed(1)}%</span>
        </div>
        <div class="compliance-item">
            <div class="compliance-name">平均日增长</div>
            <span class="compliance-rate medium">${data.trend_statistics.avg_daily_growth.toFixed(1)}</span>
        </div>
        <div class="compliance-item">
            <div class="compliance-name">峰值日期</div>
            <span class="compliance-rate">${data.trend_statistics.peak_date || '-'}</span>
        </div>
    `;

    stats.innerHTML = statsHtml;
}

// 更新变化率
function updateChangeRates(data) {
    const changeRates = document.getElementById('changeRates');
    if (!changeRates || !data || !data.change_rates) return;

    let html = '';
    Object.entries(data.change_rates).forEach(([type, rate]) => {
        const rateClass = rate >= 0 ? 'high' : 'low';
        html += `
            <div class="compliance-item">
                <div class="compliance-name">${type}</div>
                <span class="compliance-rate ${rateClass}">${rate >= 0 ? '+' : ''}${rate.toFixed(1)}%</span>
            </div>
        `;
    });

    changeRates.innerHTML = html;
}

// 更新投诉类型详情
function updateComplaintDetails(data) {
    const details = document.getElementById('complaintDetails');
    if (!details) return;

    if (!data || data.length === 0) {
        details.innerHTML = '<div class="empty-state"><i class="fas fa-inbox"></i><p>暂无投诉类型详情</p></div>';
        return;
    }

    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pageData = data.slice(startIndex, endIndex);

    let html = '';
    pageData.forEach(item => {
        const priorityClass = item.priority || 'medium';
        const priorityLabel = getPriorityLabel(item.priority || 'medium');

        html += `
            <div class="card mb-3">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h6 class="card-title mb-0">${item.complaint_type || '未分类'}</h6>
                        <span class="complaint-badge ${priorityClass}">${priorityLabel}</span>
                    </div>
                    <p class="card-text text-muted small">${item.description || '无描述'}</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <i class="fas fa-calendar"></i> ${item.created_at || '未知时间'}
                        </small>
                        <small class="text-muted">
                            <i class="fas fa-brain"></i> 置信度: ${((item.confidence || 0) * 100).toFixed(1)}%
                        </small>
                    </div>
                </div>
            </div>
        `;
    });

    details.innerHTML = html;
    updateDetailsPagination(data.length);
}

// 更新详情分页
function updateDetailsPagination(totalItems) {
    const pagination = document.getElementById('detailsPagination');
    const info = document.getElementById('detailsInfo');

    if (!pagination || !info) return;

    const totalPages = Math.ceil(totalItems / pageSize);
    const startIndex = (currentPage - 1) * pageSize + 1;
    const endIndex = Math.min(currentPage * pageSize, totalItems);

    // 更新信息
    info.textContent = `显示 ${startIndex}-${endIndex} 项，共 ${totalItems} 项`;

    // 生成分页按钮
    let paginationHtml = '';

    // 上一页
    paginationHtml += `
        <button class="btn btn-sm btn-outline-secondary" onclick="changePage(${currentPage - 1})"
                ${currentPage === 1 ? 'disabled' : ''}>
            <i class="fas fa-chevron-left"></i>
        </button>
    `;

    // 页码
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        paginationHtml += `
            <button class="btn btn-sm ${i === currentPage ? 'btn-primary' : 'btn-outline-secondary'}"
                    onclick="changePage(${i})">
                ${i}
            </button>
        `;
    }

    // 下一页
    paginationHtml += `
        <button class="btn btn-sm btn-outline-secondary" onclick="changePage(${currentPage + 1})"
                ${currentPage === totalPages ? 'disabled' : ''}>
            <i class="fas fa-chevron-right"></i>
        </button>
    `;

    pagination.innerHTML = paginationHtml;
}

// 切换页面
function changePage(page) {
    const totalPages = Math.ceil((currentData?.complaint_details?.length || 0) / pageSize);
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        updateComplaintDetails(currentData?.complaint_details || []);
    }
}

// 切换标签页
function switchTab(tabId) {
    // 更新标签按钮状态
    document.querySelectorAll('.custom-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabId}"]`).classList.add('active');

    // 显示对应内容
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.style.display = 'none';
    });

    const targetPane = document.getElementById(tabId);
    if (targetPane) {
        targetPane.style.display = 'block';
    }

    // 重新调整图表大小
    setTimeout(() => {
        Object.values(charts).forEach(chart => {
            if (chart.resize) chart.resize();
        });
    }, 100);
}

// 重置筛选条件
function resetFilters() {
    document.getElementById('taskSelect').value = '';
    document.getElementById('startDate').value = '';
    document.getElementById('endDate').value = '';
    document.getElementById('complaintType').value = '';
    document.getElementById('priority').value = '';
    document.getElementById('keywordFilter').value = '';
    document.getElementById('minConfidence').value = '';

    setDefaultDates();
    loadAnalysis();
}

// 刷新图表
function refreshChart(chartType) {
    if (!currentData) return;

    switch (chartType) {
        case 'typeDistribution':
            updateTypeDistributionChart(currentData.type_distribution);
            break;
        case 'typeTrends':
            updateTypeTrendsChart(currentData.trend_analysis);
            break;
        case 'priorityAnalysis':
            updatePriorityAnalysisChart(currentData.priority_analysis);
            break;
        case 'keywordAnalysis':
            updateKeywordAnalysisChart(currentData.keyword_analysis);
            break;
    }

    showNotification('图表已刷新', 'success');
}

// 下载图表
function downloadChart(chartType) {
    let chart;
    let filename;

    switch (chartType) {
        case 'typeDistribution':
            chart = charts.typeDistribution;
            filename = '投诉类型分布图表.png';
            break;
        case 'typeTrends':
            chart = charts.typeTrends;
            filename = '投诉类型趋势图表.png';
            break;
        case 'priorityAnalysis':
            chart = charts.priorityAnalysis;
            filename = '优先级分析图表.png';
            break;
        case 'keywordAnalysis':
            chart = charts.keywordAnalysis;
            filename = '关键词分析图表.png';
            break;
    }

    if (chart) {
        const url = chart.toBase64Image();
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        a.click();

        showNotification('图表已下载', 'success');
    }
}

// 导出详情
function exportDetails() {
    if (!currentData || !currentData.complaint_details) {
        showNotification('没有数据可导出', 'warning');
        return;
    }

    const data = currentData.complaint_details;
    const csv = convertToCSV(data);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `投诉类型详情_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();

    showNotification('详情已导出', 'success');
}

// 转换为CSV
function convertToCSV(data) {
    const headers = ['投诉类型', '优先级', '置信度', '描述', '创建时间'];
    const rows = data.map(item => [
        item.complaint_type || '',
        getPriorityLabel(item.priority || 'medium'),
        (item.confidence * 100).toFixed(1) + '%',
        item.description || '',
        item.created_at || ''
    ]);

    return [headers, ...rows].map(row =>
        row.map(field => `"${field}"`).join(',')
    ).join('\n');
}

// 刷新详情
function refreshDetails() {
    if (currentData) {
        updateComplaintDetails(currentData.complaint_details);
        showNotification('详情已刷新', 'success');
    }
}

// 显示加载状态
function showLoading(show) {
    const overlay = document.getElementById('loadingOverlay');
    if (overlay) {
        if (show) {
            overlay.classList.add('active');
        } else {
            overlay.classList.remove('active');
        }
    }
}

// 显示错误信息
function showError(message) {
    showNotification(message, 'error');
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 显示空状态
function showEmptyState(message) {
    const tabContent = document.querySelector('.tab-content-custom');
    if (tabContent) {
        tabContent.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <p>${message}</p>
            </div>
        `;
    }
}

// 更新最后更新时间
function updateLastUpdateTime() {
    const now = new Date();
    const timeString = now.toLocaleString('zh-CN');
    const element = document.getElementById('lastUpdate');
    if (element) {
        element.textContent = timeString;
    }
}

// 获取优先级标签
function getPriorityLabel(priority) {
    const labelMap = {
        'high': '高',
        'medium': '中',
        'low': '低'
    };
    return labelMap[priority] || priority;
}

// 获取优先级颜色
function getPriorityColor(priority) {
    const colorMap = {
        'high': '#ef4444',
        'medium': '#f59e0b',
        'low': '#10b981'
    };
    return colorMap[priority] || '#6b7280';
}

// 生成颜色
function generateColors(count) {
    const colors = [
        '#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6',
        '#06b6d4', '#f97316', '#84cc16', '#ec4899', '#6366f1'
    ];

    const result = [];
    for (let i = 0; i < count; i++) {
        result.push(colors[i % colors.length]);
    }
    return result;
}

// 根据索引获取颜色
function getColorByIndex(index, alpha = 1) {
    const colors = [
        `rgba(59, 130, 246, ${alpha})`,   // blue
        `rgba(239, 68, 68, ${alpha})`,    // red
        `rgba(16, 185, 129, ${alpha})`,   // green
        `rgba(245, 158, 11, ${alpha})`,   // yellow
        `rgba(139, 92, 246, ${alpha})`,   // purple
        `rgba(6, 182, 212, ${alpha})`,    // cyan
        `rgba(249, 115, 22, ${alpha})`,   // orange
        `rgba(132, 204, 22, ${alpha})`,   // lime
        `rgba(236, 72, 153, ${alpha})`,   // pink
        `rgba(99, 102, 241, ${alpha})`    // indigo
    ];
    return colors[index % colors.length];
}

// 刷新Token
async function refreshToken() {
    const token = localStorage.getItem('auth_token');
    if (token) {
        // 这里可以添加Token刷新逻辑
        return token;
    }
    return null;
}
</script>
{% endblock %}